package com.example.petstore_2.util;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import java.io.FileInputStream;
import java.io.InputStream;

public class OSSUtil {

    // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
    private static String endpoint = "https://oss-cn-beijing.aliyuncs.com";
    // 填写Bucket名称，例如examplebucket。
    private static String bucketName = "pet-store-w";
    // 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
//    private static String objectName = "exampledir/exampleobject.txt";
    private static String accessKeyId = "LTAI5tP9HXezv15MRbJmsUG1";
    private static String accessKeySecret = "oIZKjvgUM1TQW9cFR4cp43e6eL5QsU";

    // 创建OSSClient实例。
    private static OSS ossClient;


    public static boolean upload(String objectPath, InputStream inputStream) throws Exception {
        try {
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            ossClient.putObject(bucketName, objectPath, inputStream);
            System.out.println(222);
            return true;
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
            return false;
        }
    }

//    public static void main(String[] args) throws Exception{
//        InputStream inputStream = new FileInputStream("12.png");
//        upload("user/1.jpg", inputStream);
//    }
}